package hujz.java.file_server._default;

import hujz.java.file_server.FileMeta;
import hujz.java.file_server.FileMetaSaveInterface;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

public class MySQLFileMetaSaveImpl implements FileMetaSaveInterface {

    private static Logger logger = LoggerFactory.getLogger(MySQLFileMetaSaveImpl.class);

    public final static SqlSessionFactory sessionFactory = SessionFactoryUtils.create(System.getProperty("file.server.config.dir", "_default") + "/mybatis-config.xml", System.getProperty("file.server.config.dir", "_default") + "/sql/", null);

    public boolean save(FileMeta fileMeta) {
        SqlSession sqlSession = sessionFactory.openSession();
        try {
            if (fileMeta.getUuid() == null)
                fileMeta.setUuid(UUID.randomUUID().toString());

            if (fileMeta.getId() == null)
                fileMeta.setId(UUID.randomUUID().toString());

            sqlSession.insert("hujz.java.file_server.insertFileMeta", fileMeta);
            sqlSession.commit();
            return true;
        } catch (Exception e) {
            logger.error(String.format("Save file-meta failed, fileName: \"%s\", owner: \"%s\", url: \"%s\"!",
                    fileMeta.getFileName(), fileMeta.getOwner(), fileMeta.getUrl()), e);
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }
    }

    public FileMeta get(String uuid) {
        SqlSession sqlSession = sessionFactory.openSession();
        try {
            return sqlSession.selectOne("hujz.java.file_server.getFileMeta", uuid);
        } catch (Exception e) {
            logger.error(String.format("Get file-meta failed, uuid: \"%s\"!", uuid), e);
            return null;
        } finally {
            sqlSession.close();
        }
    }

    public boolean update(FileMeta fileMeta) {
        SqlSession sqlSession = sessionFactory.openSession();
        try {
            sqlSession.insert("hujz.java.file_server.insertFileMeta", fileMeta);
            sqlSession.commit();
            return true;
        } catch (Exception e) {
            logger.error(String.format("Update file-meta failed, fileName: \"%s\", owner: \"%s\", url: \"%s\"!",
                    fileMeta.getFileName(), fileMeta.getOwner(), fileMeta.getUrl()), e);
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }
    }

}
